$(function () {
  var localusers = [];

  $('#name').focus();
  $('#adduserform').submit(function () {
    var name = $('#name').val();
    $('#name').val('');

    var socket = new WebSocket("ws://"+location.host+"/ws/chat?name=" + name);

    socket.onopen = function (msg) {
      console.log("已连接成功！");
      console.log("onopen" + msg);
    }
    socket.onmessage = function (evt) {
      console.log("数据已接收..." + evt);
      var received_msg = evt.data;
      var info = JSON.parse(received_msg);
      if (info.type === 'allUser') {
        emptyUsers();
        info.users.forEach(function (value, index) {
          addUser(value, name);
        });
      } else if (info.type === 'chat') {
        sendMessage(info.from, info.msg, name);
      }
      $("#msg").append(info.msg + '<br>');
      console.log("数据已接收..." + received_msg);
    };

    socket.onclose = function () {
      // 关闭 websocket
      console.log("连接已关闭...");
    };

    $('.model').addClass('hidden');

    $('#message').focus();

    $('#sendmessage').on('click', function (event) {
      event.preventDefault();

      var message = $('#message').val();

      if (message.trim() !== '') {
        socket.send(message);
      }
      $('#message').val('');
      $('#message').focus();
      $('#img-prefix').empty();
    });

    return false;
  });

  function emptyUsers() {
    $('.user-list').empty();
  }

  function addUser(name, selfname) {
    var result = name === selfname ? "user " + " self" : "user ";
    $('.user-list').append($('<div></div>').addClass(result)
    .html('<img src="/ws/imgs/default.jpg" alt="user img">' +
        '<p class="username">' + name + '</p>'));
  }

  function sendMessage(from, msg, selfname) {
    var element = document.createElement('div');
    element.classList.add('info');

    if (selfname === from) {
      element.classList.add('myself');
    }
    if (/^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i.test(msg)){
        element.innerHTML = '<p class="author">' + filterStr(from) +
            '</p><div class="message"><img onclick="prefix_img(this)" style="width: 100%;height: 100%;object-fit:cover;" src="'+msg+'"></div>';
    } else{
        element.innerHTML = '<p class="author">' + filterStr(from) +
            '</p><div class="message">' + filterStr(msg) + '</div>';
    }
    $('.content-area').append(element);
    element.scrollIntoView(false);
  }

  //filter xss attack
  function filterStr(str) {
    var pattern = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？%+_]");
    var specialStr = "";
    for (var i = 0; i < str.length; i++) {
      specialStr += str.substr(i, 1).replace(pattern, '');
    }
    return specialStr;
  }

    layui.use('upload', function(){
        var upload = layui.upload;

        //执行实例
        var uploadInst = upload.render({
            elem: '#image-bth' //绑定元素
            ,url: '/upload/' //上传接口
            ,accept:'images'
            ,multiple: false
            ,acceptMime:'image/jpg, image/png, image/gif, image/webp'
            ,exts: 'jpg|png|gif|bmp|jpeg|webp'
            ,auto:false
            ,field:'image'
            ,choose: function(obj){
                //将每次选择的文件追加到文件队列
                var files = obj.pushFile();

                //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                obj.preview(function(index, file, result){
                    console.log(index); //得到文件索引
                    console.log(file); //得到文件对象
                    console.log(result); //得到文件base64编码，比如图片

                    $("#message").val(result);
                    $("#img-prefix").empty().append("<img style='width: 60px;overflow: hidden' src='"+result+"'>");
                    //obj.resetFile(index, file, '123.jpg'); //重命名文件名，layui 2.3.0 开始新增

                    //这里还可以做一些 append 文件列表 DOM 的操作

                    //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                    //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
                });
            }
            ,done: function(res){
                //上传完毕回调
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });
});

function prefix_img(self){
    let photos = {
        "title": "", //相册标题
        "id": 0, //相册id
        "start": 0, //初始显示的图片序号，默认0
        "data": [   //相册包含的图片，数组格式
            {
                "alt": "",
                "pid": 1, //图片id
                "src": $(self).attr("src"), //原图地址
                "thumb": "" //缩略图地址
            }
        ]
    }
    layer.photos({
        photos: photos
        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });
};